var index;
$(function(){
	console.log(localStorage.oauth_token+"----");
	//分页数据初始化
	var setSearchValue="",totalNum=0,specialNum=1,iDisplayStart=0,iDisplayLength=10,$grid,$items;
	//ajax全局设置
	$.ajaxSetup({
		timeout:30000,
		beforeSend: function(request) {
            request.setRequestHeader("X-AIRPORT-TOKEN", localStorage.getItem("oauth_token"));
        },
		error:function(xhr,status){
			layer.msg("网络连接已超时，请重新刷新！");
		}
	})
	/*$('.tabBar').find('span').on('click',function(e){
		$.each($('.tabBar').find('span'),function(i,n){
			if($(n).hasClass('current')){
				$(".specialSearch:eq("+i+")").show();
			}else $(".specialSearch:eq("+i+")").hide();
		})
	})*/
	var loadResource=function(){
		$.ajax({  
		    type: "get",     
		    url: baseURL+'/api/special/getResources',     
		    dataType: "json",   
		    contentType: "application/json",
		    success: function(result) {
		    	if(!result.flag){
		    		  layer.msg("数据错误原因："+result.message);
		    		  return;
		    	  }
		    	  if(result.flag){
			    	  var objData=result.results;
			    	  $.each(objData,function(index,resource){
			    		  if(resource.code=='special_publish'){
			    			  $('#addButton').css('display','block');
			    		  }
			    	  });
		    	  }
		    }
	   });
	}
	loadResource();
	//特情瀑布流显示
	var specialList=function(obj,page,def){
		var loadIndex=layer.load("正在努力加载中，请稍候!");
		var aoData = [];
		var globalSearch = {};
		var searchConditions = {};
		searchConditions.topic=obj;
		globalSearch.name= 'globalSearch';
		globalSearch.value= JSON.stringify(searchConditions);
		aoData.push(globalSearch);
		$.ajax({  
	    type: "GET",   
	    //url: baseURL+'/api/special/list?topic='+obj+"&iDisplayStart="+page*iDisplayLength+"&iDisplayLength="+iDisplayLength+"&t="+Math.random(),   
	    url: baseURL+'/api/special/list?iDisplayStart='+page*iDisplayLength+"&iDisplayLength="+iDisplayLength+"&t="+Math.random(),
	    dataType: "json",
	    data:aoData,
	    contentType: "application/json;charset=UTF-8", 
	    success: function(result) {
	    	   if(!result.flag){
	    		   layer.msg("数据错误原因："+result.message);
	    		   return;
	    	   }
	    	   if(result.flag){
	    	    var objData=result.results;
	    	    var html="";
	    	    if(objData!="[]" && objData.length!=0 && objData!=null){
	    		$.each(objData,function(a,obj){
	    		     html+="<div class='item f-l mt-20 ml-20' onclick='specialSetURL(\""+obj.ssid+"\",\""+obj.publishId+"\")' ssid='"+obj.ssid+"'><div class='spicailItemLine mt-10'><h5 class='f-l col-11 f-14 text-overflow' style='font-weight:bold'>"+obj.topic+"</h5><div class='f-r text-r mt-10'>"+changeLevelColor(obj.level)+"</div></div><div class='col-12'><span class='col-12 mt-5 c-999 spicailItemzCon'>"+obj.contents+"</span></div><div class='col-12'><span class='c-555 col-12 mt-10'>"+getTime(obj.publishTime)+"</span></div><div class='col-12'><div class='width60px f-l c-999 mt-10'>特情来源</div><ul class='f-l spicailItemResouse'>";
				  	 if(obj.status=="0"){
				  		 html+="<li class='spicailItemred'>"+obj.publishOrg+"</li>"
				  	 }else if(obj.status=="1"){
				  		 html+="<li class='spicailItemYellow'>"+obj.publishOrg+"</li>"
				  	 }else if(obj.status=="2" || obj.status=="11" || obj.status=="12" || obj.status=="10"){
				  		 html+="<li class='spicailItemgreen'>"+obj.publishOrg+"</li>"
				  	 }
	    		     html+="</ul></div>"
				  	 if(obj.flight!=null && obj.flight!="[]" && obj.flight.length!=0){
				  		html+="<div class='col-12'><div class='width60px c-999 mt-10 f-l'>关联航班</div><ul class='f-l spicailItemResouse'>" ;
				  		$.each(obj.flight,function(i,n){
				  			html+="<li class='spicailItemGray'>"+n+"</li>"
				  		})
				  		html+="</ul></div>"
				  	 }
			  		 if(obj.receiveList!=null && obj.receiveList!="[]" && obj.receiveList.length!=0){
				  		html+="<div class='col-12'><div class='width60px c-999 f-l mt-10'>关联信息</div><ul class='f-l spicailItemResouse'>" ;
				  		$.each(obj.receiveList,function(i,n){
				  			var receiveData=n.type=="2"?n.receiveId:n.receiveOrg;
				  			if(n.flag=="0"){
				  				html+="<li class='spicailItemred'>"+receiveData+"</li>"
				  			}else if(n.flag=="1"){
				  				html+="<li class='spicailItemYellow'>"+receiveData+"</li>"
				  			}else if(n.flag=="2" || n.flag=="11" || n.flag=="10" || n.flag=="12"){
				  				html+="<li class='spicailItemgreen'>"+receiveData+"</li>"
				  			}
				  	 	})
				  	 	html+="</ul></div>"
				  	 } 
				  	 html+="</div>";
				  	 //html+="<div><div class='col-12 c-999 mt-10'>特情时间</div><div class='col-12'>"+getTime(obj.publishTime)+"</div></div></div>";
	    		 });
	    		  if(page==0){
	    			  if(def==0){
	    				  $("#spicailContainer").html(html); 
		    			  $grid=$('#spicailContainer').masonry({  
				  			    itemSelector : '.item',  
				  			    columnWidth : 0  
				    	  });  
	    			  }else {
	    				  $("#spicailContainer").empty().html(html);
	    				  $grid.masonry('destroy');
	    				  var masonryOptions = {
	    						 itemSelector: '.item',
	    						 columnWidth: 0
	    				  };
	    				  $grid.masonry( masonryOptions);  
	    			  }
	    		  }else {
	    			  $items = $(html);
	    			  $grid.append($items).masonry('appended',$items);
	    		  }
	    		  if(result.totalcount>iDisplayLength){
	    			  totalNum=Math.ceil(result.totalcount/iDisplayLength)
	    		  }
	    		  if(objData.length<iDisplayLength){
	    			  $('#specialAddMore').hide(); 
	    			  $('#specialAddNoMore').show(); 
	    		  }else{
	    			  $('#specialAddMore').show();
	    			  $('#specialAddNoMore').hide();
	    			  if(specialNum>=totalNum){
							$('#specialAddMore').hide();
							$('#specialAddNoMore').show();
					  }
	    		  }
	    	   }else {
    			   $('#spicailContainer').empty().html("<div class='col-offset-1 mt-10'>没有数据</div>");
    			   $('#specialAddMore').hide(); 
    			   $('#specialAddNoMore').hide(); 
	    	   }
	    	   
	    	}
	    	layer.close(loadIndex);
	    	//layer.close(index);
	    }    
	 });
	};
	specialList("",0,0);
	/*if(navigator.userAgent.indexOf("MSIE")!=-1){
		$("#specialAddMore").html("下拉加载更多>>");
		$(window).scroll(function(){
			if($(window).scrollTop()==document.body.scrollHeight-document.documentElement.clientHeight-10){
				++specialNum;
				if(specialNum>totalNum){
					return false;
				}else{
					index=layer.load("数据努力加载中，请稍候!");
					specialList(setSearchValue,specialNum-1,1);	
				}
			}
		})
	}else{*/
	$("#specialAddMore").on('click',function(){
		++specialNum;
		if(specialNum>totalNum){
			return false;
		}else{
			//index=layer.load("数据努力加载中，请稍候!");
			specialList(setSearchValue,specialNum-1,1);	
		}
	})
	$(".doSearch").click(function(e){
		e.stopPropagation();
		specialNum=1;
		totalNum=0;
		var eInput=$(".searchTemplet").val();
		var topic=$.trim(eInput);
		setSearchValue=topic;
		specialList(topic,0,1);
	})
	//初始化环境
	/*var config = {
	    imCallBack: onClientEvent
	};
    var etCloud = new et_cloud(config);
	//ILINK回调
    var isNeedRelogin=true;
	function onClientEvent(event){
	    if(event.type === 'message'){
	        if(event.topic == 'chat'){
	        	var msg = $.parseJSON(event.message);
	        	if(msg.msg_type=="SEPCIAL"){
	        		$("#spicailContainer").empty();
		        	specialList("",0);
	        	}
	        }else if(event.topic == 'sys' && event.from_userid === 'kick'){
	            console.log('receive ' +  event.topic + ' message from ' + event.from_userid + ' : ' + event.message);
	            isNeedRelogin = false;
	            $.layer({
	            	  shade: [0],
	            	  area: ['auto','auto'],
	            	  dialog: {
	            	    msg: '亲，您已被踢下线！',
	            	    btns: 2,          
	            	    type: 4,
	            	    btn: ['重连','关闭'],
	            	    yes: function(){
	            	    	layer.msg("正在重连中...",1,6);
	            	    	reConnect();
	            	    }, no: function(){
	            	    	layer.msg('关闭成功',1,1)
	            	    	CloseWebPage();
	            	    }
	            	  }
	            	});
	        }
		 }else if (event.type == 'connect') {
	            //登录成功
	            console.log("登录IM成功");
	        } else if (event.type === 'reconnect') {
	            console.log('重新登录');
	        } else if (event.type === 'offline') {
	            console.log('已下线');
	        } else if (event.type === 'close') {
	            console.log('连接关闭,注销成功!');
	            if(isNeedRelogin){
	            	layer.msg("亲，您掉线了哦，请退出我的设备的控制界面，重新进入");
	            	reConnect();
	            }
	        } else if (event.type === 'error') {
	            console.log("用户名或密码错误! " + event.error.message + '(' + event.error.code + ')');
	            console.log(event.error.message + '(' + event.error.code + ')');
	        }
	}
	//方法签名
	var opt = {
	        userid: userName,
	        appkey: appkey,
	        secretkey :skey,
	        balanceServer:port,
			clean: 1,
			balanceProtocolVer:0,
			username:userName,
			token:localStorage.getItem("oauth_token")
	}
	etCloud.etConnect (opt);
	function reConnect(){
	    var intervalId = setInterval(function(){
	        if(etCloud.checkIsLogin()){
	        	console.log(etCloud.checkIsLogin())
	            //已登录不用再重登
	            clearInterval(intervalId);
	        }else{
	        	etCloud.etConnect (opt);
	            layer.msg("您已重新连接成功！",1,1);
	        }
	    },1000);
	}
	function CloseWebPage(){
		 if (navigator.userAgent.indexOf("MSIE") > 0) {
		  if (navigator.userAgent.indexOf("MSIE 6.0") > 0) {
		   window.opener = null;
		   window.close();
		  } else {
		   window.open('', '_top');
		   window.top.close();
		  }
		 }
		 else if (navigator.userAgent.indexOf("Firefox") > 0 || navigator.userAgent.indexOf("Chrome") >0) {
		  window.location.href = 'about:blank ';
		 } else {
			 window.opener = null;
			 window.open('', '_self', '');
			 window.close();
		 }
	}*/
	//定时刷新
	setInterval(function(){
		$("#spicailContainer").empty();
    	specialList("",0);
    	specialNum=1;
    	loadResource();
		//window.location.reload();
	},90000)
});
function addPage(){
	window.location.href=baseURL+"/api/special/page/add?ouath_token="+localStorage.getItem("oauth_token");
}
function specialSetURL(ssid,publishId){
	 window.location.href=baseURL+"/api/special/page/receive?ssid="+ssid+"&senderId="+publishId+"&ouath_token="+localStorage.getItem("oauth_token");
}
function getTime(t){
	 var date=new Date(t);
	 return date.getFullYear()+"-"+changeTime((date.getMonth()+1))+"-"+changeTime(date.getDate())+"&nbsp;"+changeTime(date.getHours())+":"+changeTime(date.getMinutes());
}
function changeTime(obj){
return obj<10?"0"+obj:obj;
}
function changeLevelColor(obj){
	if(obj=="T1"){
		return "<span class='specialLevel' style='background:#29c6ef'>"+obj+"</span>"
	}else if(obj=="T2"){
		return "<span class='specialLevel' style='background:#4884c2'>"+obj+"</span>"
	}else if(obj=="T3"){
		return "<span class='specialLevel' style='background:#ffc001'>"+obj+"</span>"
	}else if(obj=="T4"){
		return "<span class='specialLevel' style='background:#ff6600'>"+obj+"</span>"
	}else if(obj=="T5"){
		return "<span class='specialLevel' style='background:#da0001'>"+obj+"</span>"
	}
}